<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="DaemonSet名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.namespace"
        placeholder="命名空间"
        clearable
        style="width: 150px"
        class="filter-item"
        @change="handleNamespaceChange"
      >
        <el-option
          v-for="item in namespaceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        创建
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-refresh"
        @click="refreshList"
      >
        刷新
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="DaemonSet名称" min-width="180px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleDaemonSetDetail(row)">{{
            row.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="命名空间" width="120px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.namespace }}</span>
        </template>
      </el-table-column>
      <el-table-column label="副本状态" width="100px" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="getReplicaStatusType(row)">
            {{ row.ready || 0 }}/{{ row.desired || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="镜像" min-width="200px">
        <template slot-scope="{ row }">
          <div class="image-info">
            <span class="image-version">{{ row.image || "N/A" }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="getStatusType(row)">
            {{ getStatusText(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160px" align="center">
        <template slot-scope="{ row }">
          <span>{{ formatTime(row.created) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="mini" type="warning" @click="handleUpdateImage(row)">
            更新镜像
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 创建DaemonSet对话框 -->
    <el-dialog
      title="创建DaemonSet"
      :visible.sync="createDialogVisible"
      width="600px"
    >
      <el-form
        ref="createForm"
        :model="createForm"
        :rules="createRules"
        label-width="120px"
      >
        <el-form-item label="DaemonSet名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入DaemonSet名称"
          />
        </el-form-item>
        <el-form-item label="命名空间" prop="namespace">
          <el-select
            v-model="createForm.namespace"
            placeholder="请选择命名空间"
            style="width: 100%"
          >
            <el-option
              v-for="item in namespaceOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="容器名称" prop="containerName">
          <el-input
            v-model="createForm.containerName"
            placeholder="请输入容器名称"
          />
        </el-form-item>
        <el-form-item label="容器镜像" prop="image">
          <el-input
            v-model="createForm.image"
            placeholder="请输入容器镜像地址"
          />
        </el-form-item>
        <el-form-item label="端口配置">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addPort"
          >添加端口</el-button>
          <div
            v-for="(port, index) in createForm.ports"
            :key="index"
            class="port-item"
          >
            <el-input
              v-model="port.name"
              placeholder="端口名称"
              style="width: 120px; margin-right: 10px"
            />
            <el-input-number
              v-model="port.containerPort"
              :min="1"
              :max="65535"
              placeholder="容器端口"
              style="width: 120px; margin-right: 10px"
            />
            <el-select
              v-model="port.protocol"
              placeholder="协议"
              style="width: 100px; margin-right: 10px"
            >
              <el-option label="TCP" value="TCP" />
              <el-option label="UDP" value="UDP" />
            </el-select>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removePort(index)"
            >删除</el-button>
          </div>
        </el-form-item>
        <el-form-item label="环境变量">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addEnv"
          >添加环境变量</el-button>
          <div
            v-for="(env, index) in createForm.env"
            :key="index"
            class="env-item"
          >
            <el-input
              v-model="env.name"
              placeholder="变量名"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="env.value"
              placeholder="变量值"
              style="width: 200px; margin-right: 10px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removeEnv(index)"
            >删除</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 更新镜像对话框 -->
    <el-dialog
      title="更新镜像"
      :visible.sync="updateImageDialogVisible"
      width="400px"
    >
      <el-form :model="updateImageForm" label-width="100px">
        <el-form-item label="当前镜像">
          <span>{{ updateImageForm.currentImage }}</span>
        </el-form-item>
        <el-form-item label="新镜像" prop="image">
          <el-input
            v-model="updateImageForm.image"
            placeholder="请输入新的镜像地址"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateImageDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleUpdateImageConfirm"
        >确定</el-button>
      </div>
    </el-dialog>

    <!-- DaemonSet详情对话框 -->
    <el-dialog title="DaemonSet详情" :visible.sync="detailDialogVisible" width="80%">
      <el-descriptions v-if="currentDaemonSet" :column="2" border>
        <el-descriptions-item label="名称">{{
          currentDaemonSet.name
        }}</el-descriptions-item>
        <el-descriptions-item label="命名空间">{{
          currentDaemonSet.namespace
        }}</el-descriptions-item>
        <el-descriptions-item label="副本状态">
          {{ currentDaemonSet.ready || 0 }}/{{ currentDaemonSet.desired || 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDaemonSet)">
            {{ getStatusText(currentDaemonSet) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          formatTime(currentDaemonSet.created)
        }}</el-descriptions-item>
        <el-descriptions-item label="当前调度数">{{
          currentDaemonSet.current || 0
        }}</el-descriptions-item>
        <el-descriptions-item label="镜像" :span="2">
          <span>{{ currentDaemonSet.image || "N/A" }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <el-tag
            v-for="(value, key) in currentDaemonSet.labels"
            :key="key"
            size="small"
            style="margin-right: 5px; margin-bottom: 5px"
          >
            {{ key }}: {{ value }}
          </el-tag>
          <span
            v-if="
              !currentDaemonSet.labels ||
                Object.keys(currentDaemonSet.labels).length === 0
            "
          >无</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getDaemonSetList, createDaemonSet, updateDaemonSet, deleteDaemonSet } from '@/api/k8sDaemonSet'
import { getNameSpaceList } from '@/api/k8sNamespace'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'DaemonSetList',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        namespace: ''
      },
      namespaceOptions: [],
      allDaemonSets: [],

      // 创建对话框相关
      createDialogVisible: false,
      createForm: {
        name: '',
        namespace: '',
        image: '',
        containerName: 'app',
        ports: [
          {
            name: 'http',
            containerPort: 80,
            protocol: 'TCP'
          }
        ],
        env: []
      },
      createRules: {
        name: [
          { required: true, message: '请输入DaemonSet名称', trigger: 'blur' }
        ],
        namespace: [
          { required: true, message: '请选择命名空间', trigger: 'change' }
        ],
        containerName: [
          { required: true, message: '请输入容器名称', trigger: 'blur' }
        ],
        image: [{ required: true, message: '请输入容器镜像', trigger: 'blur' }]
      },

      // 更新镜像对话框相关
      updateImageDialogVisible: false,
      updateImageForm: {
        name: '',
        namespace: '',
        currentImage: '',
        image: ''
      },

      // 详情对话框相关
      detailDialogVisible: false,
      currentDaemonSet: null
    }
  },

  created() {
    this.getList()
    this.getNamespaces()
  },

  methods: {
    /**
     * 获取DaemonSet列表
     */
    getList() {
      this.listLoading = true

      const queryParams = {
        page: this.listQuery.page,
        limit: this.listQuery.limit
      }

      if (this.listQuery.namespace) {
        queryParams.namespace = this.listQuery.namespace
      }

      console.log('发送给后端的查询参数:', queryParams)

      getDaemonSetList(this.listQuery.namespace || 'default')
        .then((response) => {
          console.log('完整响应数据:', response)
          if (response.code === 20000) {
            const rawData = response.daemonSetList || []
            this.processAndFilterData(rawData)
          } else {
            this.$message.error(response.message || '获取列表失败')
          }
          this.listLoading = false
        })
        .catch((error) => {
          console.error('获取DaemonSet列表失败:', error)
          this.listLoading = false
          this.$message.error('获取DaemonSet列表失败')
        })
    },

    /**
     * 处理数据并应用前端过滤和分页
     */
    processAndFilterData(rawData) {
      const processedList = rawData

      // 保存全量数据用于前端分页
      this.allDaemonSets = processedList
      console.log('处理后的全量数据:', this.allDaemonSets)

      // 应用前端过滤
      let filteredList = [...this.allDaemonSets]

      // 按名称过滤（前端实现）
      if (this.listQuery.name) {
        const searchName = this.listQuery.name.toLowerCase()
        filteredList = filteredList.filter(
          (ds) =>
            ds.name && ds.name.toLowerCase().includes(searchName)
        )
        console.log(
          `按名称"${this.listQuery.name}"过滤后的数据:`,
          filteredList
        )
      }

      // 前端分页计算
      this.total = filteredList.length
      const start = (this.listQuery.page - 1) * this.listQuery.limit
      const end = start + this.listQuery.limit
      this.list = filteredList.slice(start, end)

      console.log('最终显示的数据:', this.list)
      console.log('数据条数:', this.total)
    },

    /**
     * 获取命名空间列表
     */
    getNamespaces() {
      getNameSpaceList()
        .then((response) => {
          if (response.code === 20000) {
            this.namespaceOptions = response.nameSpaceList
              ? response.nameSpaceList.map((ns) => ns.name)
              : []
          } else {
            this.$message.error(response.message || '获取命名空间失败')
          }
        })
        .catch((error) => {
          console.error('获取命名空间失败:', error)
          this.$message.error('获取命名空间失败')
        })
    },

    /**
     * 处理搜索筛选
     */
    handleFilter() {
      this.listQuery.page = 1
      if (this.allDaemonSets.length > 0) {
        this.processAndFilterData(this.allDaemonSets)
      } else {
        this.getList()
      }
    },

    /**
     * 刷新数据列表
     */
    refreshList() {
      this.listQuery.page = 1
      if (this.allDaemonSets.length > 0) {
        this.processAndFilterData(this.allDaemonSets)
      } else {
        this.getList()
      }
      this.$message.success('数据已刷新')
    },

    /**
     * 处理命名空间变化
     */
    handleNamespaceChange() {
      this.listQuery.page = 1
      this.getList()
    },

    /**
     * 处理创建DaemonSet
     */
    handleCreate() {
      this.createForm = {
        name: '',
        namespace: this.listQuery.namespace || '',
        image: '',
        containerName: 'app',
        ports: [
          {
            name: 'http',
            containerPort: 80,
            protocol: 'TCP'
          }
        ],
        env: []
      }
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createForm && this.$refs.createForm.clearValidate()
      })
    },

    /**
     * 确认创建DaemonSet
     */
    handleCreateConfirm() {
      this.$refs.createForm.validate((valid) => {
        if (valid) {
          // 构建创建请求数据
          const requestData = {
            name: this.createForm.name,
            image: this.createForm.image,
            port: this.createForm.ports[0]?.containerPort || 80,
            containerName: this.createForm.containerName,
            ports: this.createForm.ports,
            env: this.createForm.env
          }

          createDaemonSet(this.createForm.namespace, requestData)
            .then((response) => {
              if (response.code === 20000) {
                this.$message.success('创建成功')
                this.createDialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.message || '创建失败')
              }
            })
            .catch((error) => {
              console.error('创建DaemonSet失败:', error)
              this.$message.error('创建DaemonSet失败')
            })
        }
      })
    },

    /**
     * 处理更新镜像操作
     */
    handleUpdateImage(row) {
      this.updateImageForm = {
        name: row.name,
        namespace: row.namespace,
        currentImage: row.image || '',
        image: row.image || ''
      }
      this.updateImageDialogVisible = true
    },

    /**
     * 确认更新镜像操作
     */
    handleUpdateImageConfirm() {
      if (!this.updateImageForm.image) {
        this.$message.error('请输入新的镜像地址')
        return
      }

      updateDaemonSet(
        this.updateImageForm.namespace,
        this.updateImageForm.name,
        { image: this.updateImageForm.image }
      )
        .then((response) => {
          if (response.code === 20000) {
            this.$message.success('镜像更新成功')
            this.updateImageDialogVisible = false
            this.getList()
          } else {
            this.$message.error(response.message || '更新镜像失败')
          }
        })
        .catch((error) => {
          console.error('更新镜像失败:', error)
          this.$message.error('更新镜像失败')
        })
    },

    /**
     * 处理删除DaemonSet操作
     */
    handleDelete(row) {
      this.$confirm(`确定要删除DaemonSet "${row.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDaemonSet(row.namespace, row.name)
            .then((response) => {
              if (response.code === 20000) {
                this.$message.success('删除成功')
                setTimeout(() => {
                  this.getList()
                }, 1500)
              } else {
                this.$message.error(response.message || '删除失败')
              }
            })
            .catch((error) => {
              console.error('删除DaemonSet失败:', error)
              this.$message.error('删除DaemonSet失败')
            })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    /**
     * 查看DaemonSet详情
     */
    handleDaemonSetDetail(row) {
      this.currentDaemonSet = row
      this.detailDialogVisible = true
    },

    /**
     * 添加端口配置
     */
    addPort() {
      this.createForm.ports.push({
        name: '',
        containerPort: 80,
        protocol: 'TCP'
      })
    },

    /**
     * 删除端口配置
     */
    removePort(index) {
      this.createForm.ports.splice(index, 1)
    },

    /**
     * 添加环境变量
     */
    addEnv() {
      this.createForm.env.push({
        name: '',
        value: ''
      })
    },

    /**
     * 删除环境变量
     */
    removeEnv(index) {
      this.createForm.env.splice(index, 1)
    },

    /**
     * 获取副本状态类型
     */
    getReplicaStatusType(row) {
      const ready = row.ready || 0
      const desired = row.desired || 0
      if (ready === desired) return 'success'
      if (ready === 0) return 'danger'
      return 'warning'
    },

    /**
     * 获取状态类型
     */
    getStatusType(row) {
      const ready = row.ready || 0
      const desired = row.desired || 0
      if (ready === desired) return 'success'
      if (ready === 0) return 'danger'
      return 'warning'
    },

    /**
     * 获取状态文本
     */
    getStatusText(row) {
      const ready = row.ready || 0
      const desired = row.desired || 0
      if (ready === desired) return '正常'
      if (ready === 0) return '异常'
      return '部署中'
    },

    /**
     * 格式化时间戳
     */
    formatTime(timestamp) {
      if (!timestamp) return '-'
      return new Date(timestamp).toLocaleString()
    }
  }
}
</script>

<style scoped>
.link-type {
  color: #409eff;
  cursor: pointer;
}

.link-type:hover {
  text-decoration: underline;
}

.image-info {
  margin: 2px 0;
  font-size: 12px;
}

.image-version {
  color: #666;
}

.port-item,
.env-item {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}
</style>
